package com.masterclient.app.modules.order;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.eoner.baselib.enums.FCPageViewState;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.empty.FCPageStateView;
import com.eoner.baselibrary.bean.order.OrderSendDeliveryBean;
import com.eoner.baselibrary.bean.order.PayInfoBean;
import com.eoner.baselibrary.bean.order.PresentationShareBean;
import com.eoner.baselibrary.base.FragmentHostActivity;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.eoner.baselib.utils.notify.RxBus;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.businessmodule.minemodule.address.ChangeAddressActivity;
import com.eoner.baselibrary.bean.address.AddressBean;
import com.masterclient.app.modules.aftersale.CommentActivity;
import com.masterclient.app.modules.aftersale.LogistInfoActivity;
import com.eoner.baselibrary.bean.order.OrderListBean;
import com.eoner.baselibrary.bean.order.PayResult;
import com.eoner.baselibrary.bean.order.PaymentBean;
import com.masterclient.app.modules.order.adapter.SaleOrdersFilterAdapter;
import com.masterclient.app.modules.order.contract.OrderListContract;
import com.masterclient.app.modules.order.contract.OrderListPresenter;
import com.masterclient.app.modules.order.utils.MyRecyclerView;
import com.masterclient.app.widget.ShareGivingDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

import static com.masterclient.app.App.context;

/**
 * 作者：sean
 * 创建时间：2017/7/27 10:09
 * 功能说明：
 */

public class OrderListFragment extends BaseFragment<OrderListPresenter> implements OrderListContract.View {

    public static String ALL_ORDER = "get_order_list";//全部订单
    public static String UNPAID_ORDER = "get_unpaid_order";//待付款
    public static String UNDELIVERY = "get_paid_order";//待发货
    public static String UNRECIEVERED = "get_shipping_order";//待收货
    public static String UNCOMMENTED = "get_review_order";//待评价
    public static String SEARCH_ORDER = "order_search";//搜索

    @BindView(R.id.recyclerView)
    MyRecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.order_list_filter)
    RecyclerView orderListFilter;

    private List<OrderListBean.DataBean.ShDataBean> allData;
    private int page = 1;
    private int totals;
    private String update_order_id;
    private String update_trade_id;

    private OrderListAdapter orderListAdapter;
    private String type;
    private String orderType;

    private FCPageStateView emptyView;

    private PaymentMethodDialog paymentMethodDialog;
    PaymentBean.DataBean paymentBean;
    private String trade_no;
    private IWXAPI iwxapi;
    private static final int SDK_PAY_FLAG = 1;
    private String keywords = "";
    private String fromType, orderTitleType = "0", autoType = "0";

    private List<String> titleType = new ArrayList<>();
    private SaleOrdersFilterAdapter filterAdapter;
    private boolean isHelpAnim = true;
    private String is_screen = "1";

    private RxBus rxBus;
    private LinearLayoutManager linearLayoutManager;

    public static OrderListFragment getInstance(String type, String keyword, String fromType, String autoType) {
        OrderListFragment orderListFragment = new OrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("keyword", keyword);
        bundle.putString("from_type", fromType);
        bundle.putString("auto_type", autoType);
        orderListFragment.setArguments(bundle);
        return orderListFragment;
    }


    @Override
    protected View getRootView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_order_list, null);
        return view;
    }

    @Override
    protected void initOnlyOnce() {
        iwxapi = WXAPIFactory.createWXAPI(mContext, null);
        this.type = (String) getArguments().get("type");
        this.keywords = (String) getArguments().get("keyword");
        this.fromType = (String) getArguments().get("from_type");
        this.autoType = (String) getArguments().get("auto_type");

        emptyView = new FCPageStateView(getActivity());
        emptyView.setViewState(FCPageViewState.PAGE_STATE_NO_DATA,R.mipmap.icon_empty_menu,"暂无订单数据");
        emptyView.setVisibility(View.GONE);

        if ("sale".equals(fromType)&&"0".equals(autoType)){
            orderListFilter.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false));
            filterAdapter = new SaleOrdersFilterAdapter(titleType);
            filterAdapter.bindToRecyclerView(orderListFilter);
            filterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (filterAdapter.getSelectIndex() == position) return;
                    filterAdapter.setSelectIndex(position);
                    orderTitleType = String.valueOf(position);
                    is_screen = "1";
                    refresh();
                }
            });
            orderListFilter.setVisibility(View.VISIBLE);
        }else {
            orderListFilter.setVisibility(View.GONE);
        }

        orderListAdapter = new OrderListAdapter(fromType);
        linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(orderListAdapter);
        orderListAdapter.setEmptyView(emptyView);
        orderListAdapter.setOnButtonClickListener(new OrderListAdapter.OnButtonClickListener() {
            @Override
            public void recieverOrder(String id) {
                mPresenter.recieverOrder(id);
            }

            @Override
            public void removeOrder(String id) {
                mPresenter.removeOrder(id);
            }

            @Override
            public void updateAddress(String trade_id, String order_id) {
                update_trade_id = trade_id;
                update_order_id = order_id;
                Intent intent = new Intent(getActivity(),ChangeAddressActivity.class);
                if ("purchase".equals(fromType) ) {
                    intent.putExtra("isPurchase","1");
                }else {
                    intent.putExtra("isPurchase","0");
                }
                startActivityForResult(intent, 0);
            }

            @Override
            public void cancleOrder(String reason, String id) {
                mPresenter.cancleOrder("4", id);
            }

            @Override
            public void getLogistInfo(String order_id, String order_type) {
                if ("4".equals(order_type)) {
                    //物流列表
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.SEND_LOGISTIC_INFO_FRAGMENT)
                            .withString("order_id", order_id)
                            .withString("biz_type", "1")
                            .navigation();
                    FragmentHostActivity.openFragment(mContext, fragment);
                } else {
                    //物流详情
                    startActivitryWithBundle(LogistInfoActivity.class, new String[][]{{"order_id", order_id}, {"track_no", ""}, {"biz_type", "1"}});
                }
            }

            @Override
            public void toComment(String order_id) {
                startActivitryWithBundle(CommentActivity.class, new String[][]{{"order_id", order_id}});
            }

            @Override
            public void payNow(String trade_no, String type) {
                orderType = type;
                mPresenter.payNow(trade_no);
            }

            @Override
            public void payShare(String order_no) {
                mPresenter.getShareData(order_no);
            }

            @Override
            public void toUpReserve(int position, String order_id) {
                mPresenter.upReserve(position,order_id);
            }

            @Override
            public void toSend(int type, String order_id) {
                if (type == 0) {
                    mPresenter.checkGoods(-1, order_id, "check_send");
                }else {
                    ARouter.getInstance().build(AroutePath.PURCHASE_SHIPPING_ACTIVITY)
                            .withString("order_id", order_id)
                            .withInt("type", 1).navigation();
                }
            }

            @Override
            public void toPickUp(int position,String order_id,String type) {
                mPresenter.checkGoods(position,order_id, type);
            }

            @Override
            public void toSendDelivery(int position,String order_id) {
                mPresenter.checkGoods(position,order_id, "delivery_good");
            }
        });

        swipeLayout.setOnRefreshListener(() -> {
            is_screen = "0";
            refresh();
        });
        orderListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if ("purchase".equals(fromType) ) {
                    mPresenter.purchaseOrderList(String.valueOf(page), PAGE_SIZE, type);
                }else if ("sale".equals(fromType)){
                    is_screen = "1";
                    mPresenter.saleOrdersList(autoType,type, orderTitleType, is_screen,
                            String.valueOf(page), PAGE_SIZE);
                } else {
                    mPresenter.getOrderList(type, String.valueOf(page), PAGE_SIZE, keywords);
                }
            }
        }, recyclerView);

        if ("sale".equals(fromType) && "0".equals(autoType) && getActivity() instanceof DealerSaleOrdersActivity){
            ImageView iv = ((DealerSaleOrdersActivity)getActivity()).saleOrdersHelp;
            if (iv.getVisibility() == View.VISIBLE ) {
                recyclerView.setOnScrollStatusListener(new MyRecyclerView.OnScrollStatusListener() {
                    @Override
                    public void onScrollStop() {
                        if (isHelpAnim || !getUserVisibleHint()) return;
                        isHelpAnim = true;
                        iv.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (isHelpAnim) {
                                    iv.animate().translationX(0).setInterpolator(new AccelerateInterpolator(3));
                                }
                            }
                        }, 300);

                    }

                    @Override
                    public void onScrolling() {
                        if (!isHelpAnim || !getUserVisibleHint()) return;
                        isHelpAnim = false;
                        iv.animate().translationX(ScreenUtils.dp2px(50)).setInterpolator(new DecelerateInterpolator(3));
                    }
                });
            }
        }

        rxBus = RxBus.$();
        rxBus.OnEvent(rxBus.register(Config.PAY_RESULT), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                String result = (String) o;
                switch (result) {
                    case Config.PAY_SUCCESS://支付成功
                        if (paymentMethodDialog != null && paymentMethodDialog.isShowing()) {
                            paymentMethodDialog.dismiss();
                        }
                        if (isVisibleToUser && !TextUtils.isEmpty(trade_no)) {
                            startActivitryWithBundle(PaySuccessActivity.class, new String[][]{{"trade_no", trade_no}, {"convert", orderType}, {"sale_type", "purchase".equals(fromType)?"4":""}});
                        }
                        break;
                    case Config.PAY_FAILED://支付失败
                        if (paymentMethodDialog != null && paymentMethodDialog.isShowing()) {
                            paymentMethodDialog.dismiss();
                        }
//                        startActivitry(CustomerOrderActivity.class,new String[][]{{"position","1"}});
//                        showToast("支付失败");
                        break;
                }
            }
        });

        if ("purchase".equals(fromType) ) {
            mPresenter.purchaseOrderList("1", PAGE_SIZE, type);
        }else if ("sale".equals(fromType)){
            is_screen = "0";
            mPresenter.saleOrdersList(autoType,type, orderTitleType, is_screen,
                    "1", PAGE_SIZE);
//        if ("purchase".equals(fromType) || "sale".equals(fromType)) {
//            mPresenter.saleOrderList("purchase".equals(fromType) ? 0 : 1, "1", PAGE_SIZE, type, orderTitleType);
        } else {
            mPresenter.getOrderList(type, "1", PAGE_SIZE, keywords);
        }

        if ("sale".equals(fromType) && "0".equals(autoType) ){
            countDownThread = new MyThread();
            countDownThread.start();
        }
        super.initOnlyOnce();
    }

    boolean isWhile = true;
    private MyThread countDownThread;
    class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            while (true){
                isWhile = getActivity()!=null&&!((DealerSaleOrdersActivity)getActivity()).isDestroy;
                if (!isWhile){
                    countDownThread.interrupt();
                    countDownThread=null;
                    return;
                }
                try {
                    Thread.sleep(1000);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                int firstVisible = linearLayoutManager.findFirstVisibleItemPosition();
                int lastVisible = linearLayoutManager.findLastVisibleItemPosition();
                List<OrderListBean.DataBean.ShDataBean> list = orderListAdapter.getData();
                if ( list!= null && list.size()>0) {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).getSh_order().setCount_down_second(list.get(i).getSh_order().getCount_down_second()
                                == 0?0:list.get(i).getSh_order().getCount_down_second() - 1);
                        if (i >= firstVisible && i <= lastVisible && recyclerView != null) {
                            BaseViewHolder vh = (BaseViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
                            if (vh == null) continue;
                            long second = list.get(i).getSh_order().getCount_down_second();
                            LinearLayout ll = vh.getView(R.id.ll_countdown);
//                            LinearLayout saleDescLayout = ((LinearLayout) vh.getView(R.id.sale_desc_layout));
                            if (ll.getVisibility() == View.GONE){
                                continue;
                            }
                            getActivity().runOnUiThread(() -> {
                                if (second == 0){
                                    ll.setVisibility(View.GONE);
//                                    saleDescLayout.setVisibility(View.GONE);
                                }else {
                                    TimeUtil.orderBtnCountdown((TextView) vh.getView(R.id.tv_countdown),second);
                                    ll.setVisibility(View.VISIBLE);
                                }
                            });
                        }
                    }
                }
            }
        }
    }



    public void searchKeyword(String keywords) {
        this.keywords = keywords;
        is_screen = "1";
        refresh();
    }

    public void refresh() {
        page = 1;
        if (allData != null) {
            allData.clear();
            orderListAdapter.notifyDataSetChanged();
        }
        if (emptyView != null) {
            emptyView.setVisibility(View.GONE);
        }
        if (orderListAdapter != null) {
            orderListAdapter.setEnableLoadMore(true);
        }
        if (mPresenter != null) {
            if ("purchase".equals(fromType) ) {
                mPresenter.purchaseOrderList("1", PAGE_SIZE, type);
            }else if ("sale".equals(fromType)){
                mPresenter.saleOrdersList(autoType,type, orderTitleType, is_screen,
                        "1", PAGE_SIZE);
//            if ("purchase".equals(fromType) || "sale".equals(fromType)) {
//                mPresenter.saleOrderList("purchase".equals(fromType) ? 0 : 1, "1", PAGE_SIZE, type, orderTitleType);
            } else {
                mPresenter.getOrderList(type, "1", PAGE_SIZE, keywords);
            }
        }
    }

    @Override
    public void onResume() {
//        if(allData!=null){
//            allData.clear();
//            orderListAdapter.notifyDataSetChanged();
//        }
//        emptyView.setVisibility(View.GONE);
//        orderListAdapter.setEnableLoadMore(true);
//        mPresenter.getOrderList(type,"1",PAGE_SIZE);
        super.onResume();
    }

    boolean isVisibleToUser;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0 && resultCode == 103) {
            AddressBean.DataBean.ShItemsBean itemsBean = (AddressBean.DataBean.ShItemsBean) intent.getSerializableExtra("default_address");
            if (itemsBean != null) {
                mPresenter.modifyAddress(update_trade_id, update_order_id, itemsBean.getSh_id());
            }
        }
    }

    @Override
    public void showOrderList(OrderListBean.DataBean dataBean) {

        if (page == 1 && "sale".equals(fromType)) {
            if (getActivity() instanceof DealerSaleOrdersActivity) {
                if (!"1".equals(is_screen)) {
                    ((DealerSaleOrdersActivity) getActivity()).setDesc(dataBean.getSh_order_desc(), dataBean.getAuto_order_info(), dataBean.getHelp_url());
                }
                if (dataBean.getType_map() != null){
                    titleType = dataBean.getType_map();
                    filterAdapter.setNewData(titleType);
                }
            }
        }
        if (dataBean.getSh_data() != null && dataBean.getSh_data().size() > 0) {
            page++;
            if (allData == null) {
                allData = new ArrayList<>();
            }

            allData.addAll(dataBean.getSh_data());
            orderListAdapter.setNewData(allData);
//            if (dataBean.getSh_recharge_config() != null && !TextUtils.isEmpty(dataBean.getSh_recharge_config().getSh_rechargeCenterUrl())) {
//                orderListAdapter.setData(dataBean.getSh_recharge_config().getSh_rechargeCenterUrl());
//            }
        } else {
            orderListAdapter.setEnableLoadMore(false);
        }
        emptyView.setVisibility(View.VISIBLE);
        if (swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }
    }

    @Override
    public void getPaymentSuccess(PaymentBean.DataBean dataBean) {
        this.paymentBean = dataBean;
        trade_no = dataBean.getSh_trade_no();
        paymentMethodDialog = new PaymentMethodDialog(mContext, dataBean, fromType);
        paymentMethodDialog.setOnPayListener(new PaymentMethodDialog.OnPayListener() {
            @Override
            public void wxPrePay(String id) {
                if (iwxapi.isWXAppInstalled()) {
                    mPresenter.aliPrepay(trade_no,id);
                } else {
                    showToast("检测到当前设备没有安装微信");
                }
            }

            @Override
            public void zfbPrePay(String id) {
                Uri uri = Uri.parse("alipays://platformapi/startApp");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                ComponentName componentName = intent.resolveActivity(context.getPackageManager());
                if (componentName != null) {
                    mPresenter.aliPrepay(trade_no,id);
                } else {
                    showToast("检测到当前设备没有安装支付宝");
                }
            }
        });
        paymentMethodDialog.show();
    }

    @Override
    public void removeOrderSuccess() {
//        showToast("删除订单成功");
        page = 1;
        if (mPresenter != null) {
            if ("purchase".equals(fromType)) {
                mPresenter.purchaseOrderList("1", PAGE_SIZE, type);
            } else if ("sale".equals(fromType)) {
                mPresenter.saleOrdersList(autoType, type, orderTitleType, "1",
                        "1", PAGE_SIZE);
//        if ("purchase".equals(fromType) || "sale".equals(fromType)) {
//            mPresenter.saleOrderList("purchase".equals(fromType) ? 0 : 1, "1", PAGE_SIZE, type, orderTitleType);
            } else {
                mPresenter.getOrderList(type, "1", "20", keywords);
            }
        }
    }

    @Override
    public void cancleOrderSuccess() {
//        showToast("取消订单成功");
        page = 1;
        if (mPresenter != null) {
            if ("purchase".equals(fromType)) {
                mPresenter.purchaseOrderList("1", PAGE_SIZE, type);
            } else if ("sale".equals(fromType)) {
                is_screen = "1";
                mPresenter.saleOrdersList(autoType, type, orderTitleType, is_screen,
                        "1", PAGE_SIZE);
//        if ("purchase".equals(fromType) || "sale".equals(fromType)) {
//            mPresenter.saleOrderList("purchase".equals(fromType) ? 0 : 1, "1", PAGE_SIZE, type, orderTitleType);
            } else {
                mPresenter.getOrderList(type, "1", "20", keywords);
            }
        }
    }

    @Override
    public void recieverOrderSuccess() {
//        showToast("确认收货成功！");
        page = 1;
        if ("purchase".equals(fromType)) {
            mPresenter.purchaseOrderList("1", PAGE_SIZE, type);
        } else if ("sale".equals(fromType)) {
            is_screen = "1";
            mPresenter.saleOrdersList(autoType, type, orderTitleType, "1",
                    is_screen, PAGE_SIZE);
//        if ("purchase".equals(fromType) || "sale".equals(fromType)) {
//            mPresenter.saleOrderList("purchase".equals(fromType) ? 0 : 1, "1", PAGE_SIZE, type, orderTitleType);
        } else {
            mPresenter.getOrderList(type, "1", "20", keywords);
        }
    }

    @Override
    public void onDestroy() {
        rxBus.unregister(Config.PAY_RESULT);
        Log.e("=======", "fragment --> onDestroy: ");
//        isWhile = false;
        super.onDestroy();
    }

    @Override
    public void operateSuccess(int position, String msg) {
//        showToast(msg);
//        allData.clear();
//        orderListAdapter.notifyDataSetChanged();
//        orderListAdapter.setEnableLoadMore(true);
//        mPresenter.getOrderList(type,"1",PAGE_SIZE);

        if ("让上级代发成功".equals(msg)) {
            orderListAdapter.remove(position);
            if (getActivity() instanceof DealerSaleOrdersActivity) {
                ((DealerSaleOrdersActivity) getActivity()).addAutoNum();
            }
        } else {
            showToast(msg);
            Intent broadcast = new Intent();
            broadcast.setAction("refreshUnComemtedFagment");
            mContext.sendBroadcast(broadcast);
        }


    }

    @Override
    public void sendDeliverySuccess(int position, OrderSendDeliveryBean bean) {
        ToastUtil.showToast("拨货成功");
        if ("1".equals(type)){
            orderListAdapter.remove(position);
        }else {
            if (bean != null) {
                OrderListBean.DataBean.ShDataBean.ShButtonBean buttonBean = orderListAdapter.getData().get(position).getSh_button();
                OrderSendDeliveryBean.ButtonBean deliveryButtonBean = bean.getOrder_info().getButton();
                buttonBean.setAdd_track_btn(deliveryButtonBean.getAdd_track_btn());
                buttonBean.setDelivery_btn(deliveryButtonBean.getDelivery_btn());
                buttonBean.setPick_up_btn(deliveryButtonBean.getPick_up_btn());
                buttonBean.setSend_btn(deliveryButtonBean.getPick_up_btn());
                buttonBean.setUp_reserve_btn(deliveryButtonBean.getUp_reserve_btn());
                buttonBean.setView_track_btn(deliveryButtonBean.getView_track_btn());
                orderListAdapter.getData().get(position).getSh_order().setSh_status(bean.getOrder_info().getStatus());
                orderListAdapter.getData().get(position).getSh_order().setSh_status_label(bean.getOrder_info().getStatus_label());
            }else {
                orderListAdapter.getData().get(position).getSh_button().setView_track_btn("1");
            }
            orderListAdapter.notifyItemChanged(position);
        }
    }

    @Override
    public void showFail(String msg) {
        showToast(msg);
    }

    @Override
    public void loadNull() {
        orderListAdapter.setNewData(null);
        if (swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }
    }

    @Override
    public void setAliPrePayInfo(PayInfoBean.DataBean dataBean) {
        if ("1".equals(dataBean.paymentId)){
            //阿里支付
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(getActivity());
                    Map<String, String> result = alipay.payV2(dataBean.payParam.requestUrl, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }else {
            //微信支付
            iwxapi.registerApp(dataBean.payParam.appId);
            PayReq payReq = new PayReq();
            Config.APP_ID = dataBean.payParam.appId;
            payReq.appId = dataBean.payParam.appId;
            payReq.nonceStr = dataBean.payParam.nonceStr;
            payReq.packageValue = dataBean.payParam.wxPackage;
            payReq.partnerId = dataBean.payParam.partnerId;
            payReq.prepayId = dataBean.payParam.prepayId;
            payReq.timeStamp = dataBean.payParam.timestamp;
            payReq.sign = dataBean.payParam.sign;
            iwxapi.sendReq(payReq);
        }
    }

    @Override
    public void loadFailed() {
        if (swipeLayout != null && swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }
        emptyView.setVisibility(View.VISIBLE);
    }

    @Override
    public void modifyAddressSuccess(String msg) {
        if (msg != null) {
            ToastUtil.showToast(msg);
        }
    }

    @Override
    public void modifyAddressFail(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void getShareDataSuccess(PresentationShareBean shareBean) {
        ShareGivingDialog givingDialog = new ShareGivingDialog(getActivity());
        givingDialog.show();
        givingDialog.shareZsqDetail(shareBean);
    }

    @Override
    public void checkGoodsSuccess(Map<String, String> map) {
        String errorTips = map.get("error_tips");
        String jumpType = map.get("jump_type");
        if (!TextUtils.isEmpty(errorTips)) {
            ConfirmDialog dialog = new ConfirmDialog(getActivity(), "温馨提示", errorTips, null, "取消"
                    , "1".equals(jumpType) ? "去采购" : "2".equals(jumpType) ? "让上级代发" : "确定", "1".equals(jumpType) || "2".equals(jumpType) ? 0 : 1, "#FF6809");
            dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void confirm() {
                    if ("1".equals(jumpType)) {
                        ARouter.getInstance().build(AroutePath.PURCHASE_ACTIVITY).navigation();
                    }else if ("2".equals(jumpType)){
                        ConfirmDialog dialog = new ConfirmDialog(mContext, "点击确定后，该订单将会自动向上采购", "取消", "确认","#FF6809");
                        dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                            @Override
                            public void cancel() {
                                dialog.dismiss();
                            }

                            @Override
                            public void confirm() {
                                mPresenter.upReserve(Integer.parseInt(map.get("position")),map.get("relation_order_id"));
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }
                    dialog.dismiss();
                }
            });
            dialog.show();
        } else {
            if ("pick_up".equals(map.get("type"))) {
                ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY)
                        .withString("buy_type", "2")
                        .withString("saleType", "6")
                        .withString("relation_order_id", map.get("relation_order_id")).navigation();
            }else if ("delivery_good".equals(map.get("type"))) {
                mPresenter.sendDelivery(Integer.parseInt(map.get("position")),map.get("relation_order_id"));
            }else {//检测自己发货是 type对应position
                ARouter.getInstance().build(AroutePath.PURCHASE_SHIPPING_ACTIVITY)
                        .withString("order_id", map.get("relation_order_id"))
                        .withInt("type", 0).navigation();
            }
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        if (paymentMethodDialog != null && paymentMethodDialog.isShowing()) {
                            paymentMethodDialog.dismiss();
                        }
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        startActivitryWithBundle(PaySuccessActivity.class, new String[][]{{"trade_no", trade_no}, {"convert", orderType}, {"sale_type", "purchase".equals(fromType)?"4":""}});
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (paymentMethodDialog != null && paymentMethodDialog.isShowing()) {
                            paymentMethodDialog.dismiss();
                        }
//                        Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
//                        startActivitryWithBundle(CustomerOrderActivity.class,new String[][]{{"position","1"}});
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
}
